package com.scm.java.net.sup.service;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.HashedMap;

import com.scm.entity.base.DrugSns;
import com.scm.entity.base.StoDrugSale;
import com.scm.entity.base.SupDrugIn;
import com.scm.entity.base.SupDrugStock;
import com.scm.java.net.dao.CommonDao;
import com.scm.java.net.utils.StringUtils;

public class DrugSaleServiceImpl implements DrugSaleService {
	@Override
	public void add(StoDrugSale drugSale, CommonDao dao) throws Exception {
		// TODO Auto-generated method stub
		drugSale.setId(StringUtils.uniqueKey());
		dao.addObj("drugStock.addDrugSale", drugSale);
		changeDrugInAndStock(drugSale, dao);
	}

	@Override
	public void edit(StoDrugSale drugSale, CommonDao dao) throws Exception {
		// TODO Auto-generated method stub
		dao.editObj("drugStock.editSale", drugSale);
		//changeDrugInAndStock(drugSale, dao);
	}

	private void changeDrugInAndStock(StoDrugSale drugSale, CommonDao dao) throws SQLException {
		SupDrugIn drugIn = new SupDrugIn();
		drugIn.setInvoiceid(drugSale.getInvoiceid());
		Map paraMap = new HashedMap();
		paraMap.put("drugIn", drugIn);
		SupDrugIn oldDrug = (SupDrugIn) dao.queryList("drugin.getDrugins", paraMap).get(0);
		Integer amount = oldDrug.getAmount() - drugSale.getAmount();
		drugIn.setAmount(amount);
		drugIn.setTotalmoney(amount * oldDrug.getBuyprice());
		// 更新入库单
		dao.editObj("drugin.editDrug", drugIn);
		Map map = new HashedMap();
		SupDrugStock stock=new SupDrugStock();
		stock.setInvoiceid(drugSale.getInvoiceid());
		stock.setStatus(0);
		map.put("stock", stock);
		// 查出所有status为0的入库单
		List<SupDrugStock> lsns = dao.queryList("drugin.getStocks", map);
		for (int i = 0; i < drugSale.getAmount(); i++) {
			SupDrugStock s=lsns.get(i);
			s.setStatus(1);
			dao.editObj("drugStock.editStock", s);
		}
	}
}
